package com.wmx.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * RequestContextHolder 获取 ServletRequest 和 ServletResponse
 *
 * @author wangMaoXiong
 * @version 1.0
 * @date 2022/4/9 15:22
 */
@RestController
public class UserController {
    /**
     * 传统方式 通过 HttpServletRequest 获取请求参数
     * http://localhost:8080/user/clearCache1?tenant_id=440000&token=9e3bc1ba-f7cd-4754-971d-0217841e62b8
     *
     * @param request
     * @return
     */
    @GetMapping("user/clearCache1")
    @SuppressWarnings("all")
    public String clearCache1(HttpServletRequest request) {
        String tenant_id = request.getParameter("tenant_id");//参数不存在时，返回 null
        String token = request.getParameter("token");
        String result = "tenant_id=" + tenant_id + ",token=" + token;
        return result;
    }

    /**
     * 推荐方式——直接由 Spring MVC 注入参数值
     * http://localhost:8080/user/clearCache2?tenant_id=430000&token=5a9da3b3-30a5-4737-8b58-13dbed3a9a57
     *
     * @param tenant_id
     * @param token
     * @return
     */
    @GetMapping("user/clearCache2")
    public String clearCache2(Long tenant_id, String token) {
        String result = "tenant_id=" + tenant_id + ",token=" + token;
        return result;
    }

    /**
     * 在控制层以外的地方，在不接收任何参数的情况下获取 HttpServletRequest、HttpServletResponse 的特殊方式
     * 比如在静态工具类中获取
     * http://localhost:8080/user/clearCache3?tenant_id=450000&token=2f2ef709-cb50-4b43-acde-07fc1cc8f4bd
     *
     * @return
     */
    @GetMapping("user/clearCache3")
    @SuppressWarnings("all")
    public String clearCache3() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        String sessionId = servletRequestAttributes.getSessionId();

        System.out.println("】】request=" + request);
        System.out.println("】】session=" + request.getSession() + ", id=" + request.getSession().getId());
        System.out.println("】】response=" + response);
        System.out.println("】】sessionId=" + sessionId);
        System.out.println("】】realPath=" + request.getServletContext().getRealPath("/"));

        String tenant_id = request.getParameter("tenant_id");
        String token = request.getParameter("token");
        String result = "tenant_id=" + tenant_id + ",token=" + token;
        return result;
    }
}